import axios from 'axios';
import { message } from 'antd';

let qs = require('qs');
let baseURL = 'https://api-test.zjny.cc/';
let Request = axios.create();

axios.defaults.baseURL = baseURL;
Request.defaults.baseURL = baseURL;
// Request.defaults.withCredentials = false;
// const CancelToken = axios.CancelToken;
// const source = CancelToken.source();
// const loginPath = "/login"

axios.interceptors.request.use(config => {
	config.transformRequest = (data, headers) => {
		headers['Content-Type'] = 'application/x-www-form-urlencoded'
		return qs.stringify(data)
	}
    return config
}, function (error) {
    !!error.message && message.error(`REQUEST ERROR: ${error.message}`);
    return Promise.reject(error);
});

Request.interceptors.request.use(config => {

    let token: any = localStorage.getItem('token');

    // if(!memberId || !token) {
    //    return window.location.href = loginPath
    // }
    // console.log(config.url)

    config.transformRequest = (data, headers) => {
        headers['Content-Type'] = 'application/x-www-form-urlencoded'
        data = {
            ...data,
            "token": token
        }
        return qs.stringify(data)
    }
    return config
}, function (error) {
    !!error.message && message.error(`REQUEST ERROR: ${error.message}`);
    return Promise.reject(error);
});

Request.interceptors.response.use(response => {

    response.status !== 200 && message.error('网络请求失败，请稍后重试！');
    response.data.code !== 200 && !!response.data.msg && message.error(`${response.data.msg}`);
    response.data.code === 99999 && (document.location.href = '/login')
    return response;
}, function (error) {
    // !!error.message && message.error(`${error.message}`);
    return Promise.reject(error);
});

export { Request };